package com.qtu.product_service.service.impl;

import com.alibaba.fastjson.JSON;
import com.qtu.product_service.entity.ProductMapper;
import com.qtu.product_service.mapper.ElasticSearchMapper;
import com.qtu.product_service.service.ElasticSearchService;
import com.qtu.util.ES_Const;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {
    @Autowired
    private ElasticSearchMapper elasticSearchMapper;//查询数据库
    @Resource
    private RestHighLevelClient client;

    /**
     * 查询数据库所有商品并存入 ElasticSearch
     * @return
     */
    @Override
    public boolean saveAll() throws IOException {
        List<ProductMapper> mappers = elasticSearchMapper.selectAll();
        BulkRequest request = new BulkRequest();//1、创建请求
        for (ProductMapper mapper : mappers) {//2、批量插入数据
            request.add(new IndexRequest(ES_Const.PRODUCT_INDEX).id(String.valueOf(mapper.getId()))
                    .source(JSON.toJSONString(mapper),XContentType.JSON));
        }
        //2、执行
        BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
        return !bulk.hasFailures();//规则：判断是否失败？成功返回：false
    }

    /**
     * 查询
     *  1、SearchRequest：搜索请求
     *  2、SearchSourceBuilder：搜索条件 例如：设置高亮字段和分页
     *  3、QueryBuilders：条件工具类
     * @return
     */
    @Override
    public List<Map<String, Object>> search(String key) throws IOException {
        //1、创建请求
        SearchRequest request = new SearchRequest(ES_Const.PRODUCT_INDEX);

        //2、构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //3、查询条件    termQuery:精确匹配
        QueryBuilder termQuery = QueryBuilders.matchQuery("goodsName", key);

        //4、设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("goodsName");//标题
        highlightBuilder.requireFieldMatch(false);//多个字段高亮！false：只设置一个
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");

        sourceBuilder.highlighter(highlightBuilder);//字段高亮
        sourceBuilder.query(termQuery);//精确匹配
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));//设置超时时间60秒

        //5、条件置于请求之中
        request.source(sourceBuilder);

        //6、执行
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);

        //7、返回结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit result : search.getHits().getHits()) {

            Map<String, Object> sourceAsMap = result.getSourceAsMap();//获取原来结果
            Map<String, HighlightField> hit = result.getHighlightFields();//解析高亮字段
            HighlightField goodsName = hit.get("goodsName");
            if(goodsName != null){//如果存在
                Text[] texts = goodsName.getFragments();
                String name = "";
                for (Text text : texts) {
                    name += text;
                }
                sourceAsMap.put("goodsName",name);//将原来的字段替换为高亮字段
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
